package cn.chendd.tips.examples.varible;

import javassist.*;
import javassist.bytecode.*;
import org.junit.Test;

/**
 * 使用Javassit实现
 * @author chendd
 * @date 2019-08-09 22:39:20
 */
public class GetDefinitionByJavassist extends BaseTest {

    public GetDefinitionByJavassist() throws NoSuchMethodException {
    }
    
    @Test
    public void testJavassitVariable() throws NotFoundException {

        ClassPool classPool = ClassPool.getDefault();
        CtClass ctClass = classPool.getCtClass(super.getClass().getName());
        CtMethod ctMethods[] = ctClass.getMethods();
        String methodName = "sayHello";
        for (CtMethod ctMethod : ctMethods) {
            if(! methodName.equals(ctMethod.getName())){
                continue;
            }
            MethodInfo methodInfo = ctMethod.getMethodInfo();
            CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
            LocalVariableAttribute attribute = (LocalVariableAttribute) codeAttribute.getAttribute("LocalVariableTable");//LocalVariableTable
            int lens = attribute.tableLength();
            for (int i = 1; i < lens; i++) {
                System.out.print(attribute.variableName(i) + ",\t");
            }

        }
    }
}
